package com.web.system.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.util.CommonUtil;
import com.web.system.po.LoginPo;
import com.web.system.po.UserPo;
import com.web.system.service.UserService;


@Service("userService")
@Transactional(rollbackFor = { Exception.class })
public class UserDAO implements UserService {

	@Resource 
	private SessionFactory sessionFactory;
	
	/**
	 * 检查登录是否成功
	 */
	public boolean checkLogin(LoginPo login) {
		// TODO Auto-generated method stub
		Session session = null;
    	Query query = null;
      	try {
      		 session = this.sessionFactory.getCurrentSession();
      		 String queryString = "select count(*) from UserPo where userName='"+login.getUserName()+"' and password = '"+login.getPassword()+"'";
      		 query = session.createQuery(queryString); 
      		 int count = ((Long)query.uniqueResult()).intValue();
      		 return count > 0 ? true : false;
      	} catch (Exception e) {
			// TODO: handle exception
      		e.printStackTrace();
		} 
		return false;
	}
	
	
	@SuppressWarnings("unchecked")

	public List<UserPo> getUserList(String queryString ,int first,int pageSize) {
		// TODO Auto-generated method stub
		Session session = null;
    	Query query = null;
      	try {
      		 session = this.sessionFactory.getCurrentSession();
      		 query = session.createQuery(queryString);
             query.setFirstResult(first);
             query.setMaxResults(pageSize);
             List<UserPo> users = query.list(); 
             return users;
      	} catch (Exception e) {
			// TODO: handle exception
      		e.printStackTrace();
		} 
		return null;
	}


	public int getTotal(String sql) {
		// TODO Auto-generated method stub
		Session session = null;
    	Query query = null;
      	try {
      		 session = this.sessionFactory.getCurrentSession();
      		 String queryString = "select count(*) from UserPo as user where 1=1 " + sql;
      		 query = session.createQuery(queryString);       
      		 int count = ((Long)query.uniqueResult()).intValue();
      		return count;
      	} catch (Exception e) {
			// TODO: handle exception
      		e.printStackTrace();
		} 
		return 0;
	}


	public boolean saveOrUpdateUser(UserPo user) {
		// TODO Auto-generated method stub
		Session session = null;
      	try {
      		 session = this.sessionFactory.getCurrentSession();
      		 session.saveOrUpdate(user);
      		 return true;
      	} catch (Exception e) {
			// TODO: handle exception
      		e.printStackTrace();
      		throw new RuntimeException();
		} 
	}


	public UserPo getUserByUserId(String userId) {
		// TODO Auto-generated method stub
		Session session = null;
		Query query = null;
      	try {
      		session = this.sessionFactory.getCurrentSession();
  			StringBuffer hql = new StringBuffer();
    		hql.append("Select a From UserPo a");
    		hql.append(" left outer join fetch a.roleBeans");
    		hql.append(" where a.userId = '");
    		hql.append(userId);
    		hql.append("'");
            query = session.createQuery(hql.toString());
            UserPo user = (UserPo)query.list().get(0);
            return user;
      	} catch (Exception e) {
			// TODO: handle exception
      		e.printStackTrace();
		} 
		return null;
	}


	public int deleteUsersBySql(String sql) {
		// TODO Auto-generated method stub
		Session session = null;
    	Query query = null;
      	try {
      		 session = this.sessionFactory.getCurrentSession();
      		 query = session.createQuery(sql);
      		 int count = query.executeUpdate();
             return count;
      	} catch (Exception e) {
			// TODO: handle exception
      		e.printStackTrace();
      		throw new RuntimeException();
		} 
	}


	public UserPo getUserByLogin(LoginPo login) {
		// TODO Auto-generated method stub
		Session session = null;
    	Query query = null;
      	try {
      		 session = this.sessionFactory.getCurrentSession();
   			 StringBuffer hql = new StringBuffer();
    		 hql.append("Select a From UserPo a");
    		 hql.append(" left outer join fetch a.roleBeans");
    		 hql.append(" where a.userName = '");
    		 hql.append(login.getUserName());
    		 hql.append("' and a.password = '");
    		 hql.append(login.getPassword());
    		 hql.append("'");
      		 query = session.createQuery(hql.toString()); 
      		 query.setMaxResults(1);
      		 return (UserPo) query.uniqueResult();
      	} catch (Exception e) {
			// TODO: handle exception
      		e.printStackTrace();
		} 
		return null;
	}


	/**
	 * 重名
	 */

	public boolean isExistUser(String name) {
		// TODO Auto-generated method stub
		
		if(name == null || "".equals(name) || "null".equalsIgnoreCase(name)){
			return false;
		}
		String []names = name.split(",");
		Session session = null;
		Query query = null;
		int count = 0;
		try {
			for (int i = 0; i < names.length; i++) {
				count = 0;
				String sql = "select count(*) from UserPo where userName = '"+names[i]+"'";
				session = this.sessionFactory.getCurrentSession();
				query = session.createQuery(sql);
				query.setMaxResults(1);
				count = ((Long)query.uniqueResult()).intValue();
				if(count < 1) {
					return false;
				}
			}
			return count > 0 ? true : false;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} 
		return false;
	}


	@SuppressWarnings("unchecked")

	public List<UserPo> getAllUsers(String way , UserPo userPo) {
		// TODO Auto-generated method stub
		Session session = null;
    	Query query = null;
      	try {
      		 String hql = "from UserPo";
      		 if("exceptMe".equals(way)){
      			 hql = "from UserPo where userId != " + userPo.getUserId();
      		 }
      		 session = this.sessionFactory.getCurrentSession();
      		 query = session.createQuery(hql);
             List<UserPo> users = query.list(); 
             return users;
      	} catch (Exception e) {
			// TODO: handle exception
      		e.printStackTrace();
		} 
		return null;
	}


	public int cancleUser(String longDate) {
		// TODO Auto-generated method stub
		Session session = null;
		SQLQuery query = null;
		try {
			if(CommonUtil.isNotNull(longDate)){
				session = this.sessionFactory.getCurrentSession();
				String sql = "delete from t_userinfo where loginTime <= SUBDATE(CURDATE(),INTERVAL "+longDate+" month) and  isnull(loginTime) is false";
				query = session.createSQLQuery(sql);
				return query.executeUpdate();
			} else{
				return -1;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return -1;
	}


	public int deleteUsers(String[] userIds) {
		// TODO Auto-generated method stub
		try {
			if(userIds != null && userIds.length > 0){
				for (int i = 0; i < userIds.length; i++) {
					UserPo userPo = getUserByUserId(userIds[i]);
					userPo.setIsDelete(1);
					saveOrUpdateUser(userPo);
				}
				return userIds.length;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return 0;
	}

}
